import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['Times New Roman']

styles = ['-', '-.', '--', ':', 'solid',
          'dashed', 'dotted', 'dashdot', 'dashed']
markers = [' ', '>', '8', '*', 'x', '+', 'p', 'D']
colors = ["red", "orange", "blue", "c", "cyan",
          "brown", "mediumvioletred", "dodgerblue", "green"]


def load_a_file_res(filename):
    """
    读取一个结果文件
    """
    with open(filename, 'r') as f:
        row_list = f.read().splitlines()
    a_day_res = row_list[0].split('|')
    a_day_res = [int(i) for i in a_day_res]
    return a_day_res


def make_filename_list(prefix):
    coe_list = ['1_2', '1_5', '1_8', '2_0']
    un_server_num_list = [100, 200]
    time_list = [12]
    res = []
    for t in time_list:
        for coe in coe_list:
            for num in un_server_num_list:
                res.append(f'{prefix}/16_{t}_{coe}_{num}.txt')
    return res


def load_many_files_res(filename_list):
    """
    将某方法多个结果文件汇总成一组数据
    然后得出统计量，提供画图数据
    """
    res = []
    for filename in filename_list:
        res += load_a_file_res(filename)
    return res


def draw_plot(data_dict):
    """
    Input: 接受任意数量的数据，key充当画图的图例，value是画图用的原始数据
    """
    plt.figure(figsize=(8, 4))
    # 适配曲线数量
    count = 0
    for k, data in data_dict.items():
        x = []
        size = len(data)
        for i in range(size):
            x.append(i)
        # plt.bar(x, data, #label=k,
        #          linestyle=styles[count], color=colors[count], linewidth=2.5)

        # sns.lineplot(x, data, label=k, linestyle=styles[count], color=colors[count], linewidth=2.5)
        plt.plot(x, data, label=k, linestyle=styles[count], color=colors[count], linewidth=2.5)
        count += 1

    # plt.ylim(1000, 5000)
    # plt.xlim(0, 22)
    plt.yticks(fontsize=20)
    plt.xticks(fontsize=20)
    plt.xlabel("Time(h)", fontsize=20)
    plt.ylabel("Error", fontsize=20)
    plt.grid()
    plt.legend()
    # plt.legend(ncol=5, loc='lower center', bbox_to_anchor=(0.6, 0), fontsize=15, framealpha=0.5,
    #     borderpad=0.1,handletextpad=0.1, handlelength=1, columnspacing=0.2)
    return plt

def draw_cdf_from_dict(data_dict):
    """绘制CDF图
    Input: 接受任意数量的数据，key充当画图的图例，value是画图用的原始数据
    """
    plt.figure(figsize=(6, 4))
    # 适配曲线数量
    count = 0
    for k, data in data_dict.items():
        x = sorted(data)
        y = []
        size = len(x)
        for i in range(size):
            # y.append(1 - i / size)
            y.append(i / size)
        plt.plot(x, y, label=k,
                 linestyle=styles[count], color=colors[count], linewidth=2.5)
        count += 1

    # plt.ylim(0.001, 1)
    # plt.xlim(0, 20)
    plt.yticks(fontsize=17)
    plt.xticks(fontsize=17)
    # plt.yscale("symlog", linthreshy=0.0001)
    plt.xlabel("x(ms)", fontsize=19)
    plt.ylabel("CDF", fontsize=19)
    plt.grid()
    plt.legend(fontsize = 20)
    # plt.legend(bbox_to_anchor=(0, 1.02, 1, 0.2), loc="lower center",
    #            mode="expand", borderaxespad=0, ncol=3, frameon=False, fontsize=14)
    return plt


if __name__ == "__main__":
    # 单个文件结果
    # max_flow_overload = load_a_file_res('./max_flow_overload_fix/16_12_3_0_100.txt')
    # max_flow_best_overload = load_a_file_res('./max_flow_best_overload_fix/16_12_3_0_100.txt')


    # 汇总多个文件结果
    max_flow_overload_filenames = make_filename_list('./max_flow_overload_fix')
    max_flow_overload = load_many_files_res(max_flow_overload_filenames)


    max_flow_best_overload_filenames = make_filename_list('./max_flow_best_overload_fix')
    max_flow_best_overload = load_many_files_res(max_flow_best_overload_filenames)

    linear_best_minloss_overload_filenames = make_filename_list('./linear_best_minloss_overload')
    linear_best_minloss_overload = load_many_files_res(linear_best_minloss_overload_filenames)

    linear_best_rand_overload_filenames = make_filename_list('./linear_best_rand_overload')
    linear_best_rand_overload = load_many_files_res(linear_best_rand_overload_filenames)

    linear_minloss_overload_filenames = make_filename_list('./linear_minloss_overload')
    linear_minloss_overload = load_many_files_res(linear_minloss_overload_filenames)

    linear_rand_overload_filenames = make_filename_list('./linear_rand_overload')
    linear_rand_overload = load_many_files_res(linear_rand_overload_filenames)

    max_fix_overload_filenames = make_filename_list('./max_fix_overload')
    max_fix_overload = load_many_files_res(max_fix_overload_filenames)

    max_best_fix_overload_filenames = make_filename_list('./max_best_fix_overload')
    max_best_fix_overload = load_many_files_res(max_best_fix_overload_filenames)


    data_dict = {
        # 'max_flow_overload': max_flow_overload,
        # 'max_flow_best_overload': max_flow_best_overload,
        'max_fix_overload': max_fix_overload,
        'max_best_fix_overload': max_best_fix_overload,
        'linear_best_minloss_overload': linear_best_minloss_overload,
        'linear_best_rand_overload': linear_best_rand_overload,
        'linear_minloss_overload': linear_minloss_overload,
        'linear_rand_overload': linear_rand_overload,
    }

    pt = draw_cdf_from_dict(data_dict)
    # pt = draw_plot(data_dict)
    pt.show()
